package com.siemens.rebbitmq.porducer;

import java.util.UUID;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.siemens.common.utils.GsonUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 单例的消息发送
 * 
 * @author P0081447
 *
 */
@Component
@Slf4j
public class PorducerFactroy {

	// 由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
	private RabbitTemplate rabbitTemplate;

	/**
	 * 构造方法注入rabbitTemplate
	 */
	@Autowired
	public PorducerFactroy(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
	}

	/**
	 * 发送消息
	 * 
	 * @param exchange   交换机
	 * @param routingKey 路由键
	 * @param data       数据
	 * @param <T>        数据类型
	 */
	public <T> void sendMsg(String exchange, String routingKey, T data) {
		log.info("send message");
		CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
		String s = GsonUtil.BeanToJson(data);
		rabbitTemplate.convertAndSend(exchange, routingKey, s, correlationId);
	}

}
